import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class controller extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private DBcontroller BD = new DBcontroller();

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String which = request.getParameter("request").toString();
		RequestDispatcher rd = null;
		
		if(which.equals("cadastro")) {
			String login = String.valueOf(request.getParameter("usuario"));
			String pass = String.valueOf(request.getParameter("password"));
			String tipo = String.valueOf(request.getParameter("tipo"));
			String nome = String.valueOf(request.getParameter("nome"));
			String rg = String.valueOf(request.getParameter("rg"));
			String cpf = String.valueOf(request.getParameter("cpf"));
			String endereco = String.valueOf(request.getParameter("endereco"));
			String telefone = String.valueOf(request.getParameter("telefone"));
			String email = String.valueOf(request.getParameter("email"));
			int dia = Integer.parseInt(request.getParameter("dia"));
			int mes = Integer.parseInt(request.getParameter("mes"));
			int ano = Integer.parseInt(request.getParameter("ano"));
			String sexo = String.valueOf(request.getParameter("sexo"));
			if(BD.Cadastrar(login, pass, tipo, nome, rg, cpf, endereco, telefone, email, dia, mes, ano, sexo)) {
				request.getSession().setAttribute("password", pass);
				request.getSession().setAttribute("userName", login);
				request.getSession().setAttribute("loginState", "logged");
				request.getSession().setAttribute("tipo",tipo);
				request.setAttribute("cadastroStatus", "Sucesso");
				
				rd = request.getRequestDispatcher("index.jsp");
			} else {
				request.setAttribute("cadastroStatus", "Erro");
				rd = request.getRequestDispatcher("index.jsp");
			}
		} else if(which.equals("changepass")) {
			String oldpass = request.getParameter("oldPass");
			String newpass = request.getParameter("newPass");
			String usuario = (String)request.getSession().getAttribute("userName");
			if(BD.ChangePass(oldpass, newpass, usuario)) {
			request.getSession().setAttribute("message", "Alteracao de password feita com sucesso!");
			} else {
			request.getSession().setAttribute("message", "Alteracao de password falhou!");	
			}
			rd = request.getRequestDispatcher("index.jsp");
		} else if(which.equals("login")) {
			String usuario = String.valueOf(request.getParameter("usuario"));
			String senha = String.valueOf(request.getParameter("password"));
			String tipo = BD.Login(usuario, senha);
			if(tipo != null)
			{
				request.getSession().setAttribute("loginState", "logged");
				request.getSession().setAttribute("userName", usuario);
				request.getSession().setAttribute("password", senha);
				request.getSession().setAttribute("tipo", tipo);
				
				//redirect to successful login page
				String page = String.valueOf(request.getSession().getAttribute("currentPage"));
				if(page == null)
					page = "index.jsp";
				
				//display welcome message
				request.setAttribute("message", "Login com sucesso.");	
				rd = request.getRequestDispatcher(page);

			}
			else
			{
				
				String page = String.valueOf(request.getSession().getAttribute("currentPage"));
				if(page == null)
					page = "index.jsp";
				request.setAttribute("message", "Erro no login.");
				rd = request.getRequestDispatcher(page);
			}
		} else if (which.equals("logout")) {
			request.getSession().invalidate();
			request.setAttribute("message", "Adios Amigo!");
			rd = request.getRequestDispatcher("index.jsp");
		} else if (which.equals("atrT")) {
			request.getSession().setAttribute("currentOp", "selectAT");
			request.getSession().setAttribute("usuarios", BD.getListUsuarios("avaliador"));
			request.getSession().setAttribute("trabalhos", BD.getListTrabalhos(null));
			rd = request.getRequestDispatcher("list.jsp");
		} else if (which.equals("atrN")) {
			request.getSession().setAttribute("usuarios", BD.getListUsuarios(null));
			request.getSession().setAttribute("niveis", getListNiveis());
			request.getSession().setAttribute("currentOp", "selectAN");
			rd = request.getRequestDispatcher("list.jsp");
		} else if(which.equals("setNivel")) {
			ArrayList<String> usuarios = (ArrayList<String>) request.getSession().getAttribute("usuarios");
			String usuario = usuarios.get(Integer.parseInt(request.getParameter("index")));
			String nivel = getListNiveis().get(Integer.parseInt(request.getParameter("index2")));
			BD.setNivel(usuario, nivel);
			request.getSession().setAttribute("currentOp", null);
			rd = request.getRequestDispatcher("index.jsp");
		} else if(which.equals("setTrabalho")) {
			ArrayList<String> usuarios = (ArrayList<String>) request.getSession().getAttribute("usuarios");
			String usuario = usuarios.get(Integer.parseInt(request.getParameter("index")));
			ArrayList<String> trabalhos = (ArrayList<String>) request.getSession().getAttribute("trabalhos");
			String trabalho = trabalhos.get(Integer.parseInt(request.getParameter("index2")));
			BD.setAssocTrabalho(usuario, trabalho);
			request.getSession().setAttribute("currentOp", null);
			rd = request.getRequestDispatcher("index.jsp");
		} else if(which.equals("avaliarTrabalho")) {
			String usuario = (String)request.getSession().getAttribute("userName");
			request.getSession().setAttribute("trabalhos", BD.getListTrabalhos(usuario));
			rd = request.getRequestDispatcher("trabalhos.jsp");
		} else if(which.equals("mostrarFormAvaliacao")) {
			ArrayList<String> trabalhos = (ArrayList<String>) request.getSession().getAttribute("trabalhos");
			String trabalho = trabalhos.get(Integer.parseInt(request.getParameter("index")));
			request.getSession().setAttribute("trabalhoescolhido", trabalho);
			File file = BD.getFile(trabalho);
			request.getSession().setAttribute("file", file);
			request.getSession().setAttribute("filename", file.getName());
			rd = request.getRequestDispatcher("trabalhos_link.jsp");
		} else if(which.equals("avaliar")) {
			int nota = Integer.parseInt(request.getParameter("nota"));
			String comentario = request.getParameter("comentario");
			String avaliador = (String)request.getSession().getAttribute("userName");
			String trabalho = (String)request.getSession().getAttribute("trabalhoescolhido");
			BD.setAvaliacao(trabalho, avaliador, nota, comentario);
			rd = request.getRequestDispatcher("index.jsp");
		} else if(which.equals("download")) {
			File file = (File) request.getSession().getAttribute("file");
			ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = getServletConfig().getServletContext();
	        String              mimetype = context.getMimeType(file.getName());
	        
	        response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
	        response.setContentLength( (int)file.length() );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + file.getName() + "\"" );

	        //
	        //  Stream to the requester.
	        //
	        byte[] bbuf = new byte[4096];
	        DataInputStream in = new DataInputStream(new FileInputStream(file));

	        int length;
	        while ((in != null) && ((length = in.read(bbuf)) != -1))
	        {
	            op.write(bbuf,0,length);
	        }

	        in.close();
	        op.flush();
	        op.close();
		} else if(which.equals("upload")) {
			boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
			boolean test = false;
			if (isMultipart)
			{  
				// Create a new file upload handler
				FileItemFactory factory = new DiskFileItemFactory();
				ServletFileUpload upload = new ServletFileUpload(factory);
			
				//Parse the request
				List items;
					try {
						items = upload.parseRequest(request);

					// Process the uploaded items
					Iterator iter = items.iterator();
					String titulo = null;
					String fileName = null;
		    	    String path = "/files/mc436/"+request.getSession().getAttribute("userName")+"/";
					while (iter.hasNext()) {
					    FileItem item = (FileItem) iter.next();
					    if (item.isFormField()) {
					       //TODO work with no file field
					    	titulo = item.getString();
					    } else {
				    	    fileName = item.getName();
			    	        new File(path).mkdirs();
				    	    File uploadedFile = new File(path+fileName);
			    	        item.write(uploadedFile);
			    	
					    }
					}
					    String usuario = (String) request.getSession().getAttribute("userName");
						test = BD.setFile(usuario,titulo, path+fileName);
					} catch (FileUploadException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
		    }
			if(test) {
			rd = request.getRequestDispatcher("upload.jsp");
			} else {
		    rd = request.getRequestDispatcher("index.jsp");	
			}
		} else if(which.equals("download")) {
			rd = request.getRequestDispatcher("index.jsp");
		}

		rd.forward(request, response);

	}



	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// same logic
		this.doGet(request, response);
	}

	private ArrayList<String> getListNiveis() {
		ArrayList<String> t = new ArrayList<String>();
		t.add("avaliador");
		t.add("autor");
		t.add("chair");
		return t;
	}	
}